package util;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.ansj.splitWord.analysis.ToAnalysis;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

public class Relate {
	public static final String url = "jdbc:mysql://127.0.0.1/SearchEngine?useUnicode=true&characterEncoding=UTF-8";
	public static final String name = "com.mysql.jdbc.Driver";
	public static final String user = "root";
	public static final String password = "33505832";

	public static void main(String[] args) throws Exception {
		Connection conn = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		Class.forName(name);
		// 指定连接类型
		conn = (Connection) DriverManager.getConnection(url, user, password);// 获取连接
		// 获取字段
		String sql = "select * from pages LIMIT 30";
		pst = (PreparedStatement) conn.prepareStatement(sql);// 准备执行语句
		rs = pst.executeQuery();
		Map<String, Integer> map = new HashMap<String, Integer>();
		while (rs.next()) {
			String str = rs.getString("title");
			System.out.println(str);
			String a = ToAnalysis.parse(str).toString();
			String deal = a.substring(1, a.length() - 1);
			String after[] = deal.split(",");
			for (int i = 0; i < after.length; i++) {
				String flag[] = after[i].trim().split("/");
				if (flag[0].length() > 1) {
					// 如果Map中存在
					if (null != map.get(flag[0])) {
						int q = map.get(flag[0]);
						map.replace(flag[0], q, q + 1);
					} else {
						map.put(flag[0], 0);
					}
				}
			}
		}
		// 获取词语出现次数的Map之后进行排序
		List arrayList = new ArrayList(map.entrySet());
		Collections.sort(arrayList, new Comparator() {
			public int compare(Object o1, Object o2) {
				Map.Entry obj1 = (Map.Entry) o1;
				Map.Entry obj2 = (Map.Entry) o2;
				return ((Integer) obj2.getValue()).compareTo((Integer) obj1.getValue());
			}
		});

		for (int i = 0; i < arrayList.size(); i++) {
			System.out.println(arrayList.get(i));
		}
		String one[] = arrayList.get(0).toString().split("=");
		String two[] = arrayList.get(1).toString().split("=");
		String three[] = arrayList.get(2).toString().split("=");
		// 执行插入语句
		String ins = "INSERT INTO relate (keyword,one,one_number,two,two_number,three,three_number) VALUES (\"" + "人际"
				+ "\",\" " + one[0].trim() + "\",\"" + one[1].trim() + "\",\" " + two[0].trim() + "\",\" "
				+ two[1].trim() + "\",\" " + three[0].trim() + "\",\" " + three[1].trim() + "\")";
		pst = (PreparedStatement) conn.prepareStatement(ins);// 准备执行语句
		pst.execute();
		conn.close();
		pst.close();
	}
}
